import 'package:flutter/material.dart';
import 'package:httpdio/screens/posts_screen.dart';
import 'package:provider/provider.dart';
import '../models/comment_model.dart';
import '../models/post_model.dart';
import '../models/user_model.dart';
import '../service/comment_service.dart';
import '../service/post_service.dart';
import '../service/user_service.dart';
import '../widgets/error_widget.dart';
import '../widgets/user_form_dialog.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'comments_screen.dart';
import 'posts_screen.dart'; // 确保已导入帖子页面
class UserScreen extends StatefulWidget {
  const UserScreen({super.key});

  @override
  _UserScreenState createState() => _UserScreenState();
}

class _UserScreenState extends State<UserScreen>     with SingleTickerProviderStateMixin{
  late Future<List<User>> _futureUsers;
  bool _isLoading = false;
  late TabController _tabController;
  int _currentTabIndex = 0;
  @override
  void initState() {
    super.initState();
    _loadUsers();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _currentTabIndex = _tabController.index;
      });
    });
  }

  void _loadUsers() {
    setState(() {
      _futureUsers = context.read<UserService>().getUsers();
    });
  }
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _loadUsers,
          ),
          if (_currentTabIndex == 0)
            IconButton(
              icon: const Icon(Icons.add),
              onPressed: () => _showAddUserDialog(context),
            ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '用户列表', icon: Icon(Icons.people)),
            Tab(text: '用户帖子', icon: Icon(Icons.article)),
            Tab(text: '用户评论', icon: Icon(Icons.comment)),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () => _showAddUserDialog(context),
      ),
      // body: _buildUserList(),
      body:   TabBarView(
        controller: _tabController,
        children: [
          _buildUserList(),
          _buildUserPostsTab(),
          _buildUserCommentsTab(),
        ],
      ),
    );
  }

  Widget _buildUserList() {
    return FutureBuilder<List<User>>(
      future: _futureUsers,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting && !snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return CustomErrorWidget(
            message: snapshot.error.toString(),
            onRetry: _loadUsers,
          );
        }

        final users = snapshot.data ?? [];

        if (users.isEmpty) {
          return _buildEmptyState();
        }

        return ListView.builder(
          itemCount: users.length,
          itemBuilder: (context, index) => _buildUserItem(users[index]),
        );
      },
    );
  }

  Widget _buildUserItem(User user) {
    return Slidable(
      endActionPane: ActionPane(
        motion: const ScrollMotion(),
        children: [
          // 编辑按钮
          SlidableAction(
            onPressed: (context) => _showEditUserDialog(context, user),
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
            icon: Icons.edit,
            label: '编辑',
          ),
          // 删除按钮
          SlidableAction(
            onPressed: (context) => _deleteUser(user.id),
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
            icon: Icons.delete,
            label: '删除',
          ),
        ],
      ),
      child: ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage(user.avatarUrl),
        ),
        title: Text(user.displayName),
        subtitle: Text(user.email),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        onTap: () => _showUserDetails(context, user),
      ),
    );
  }

// 添加确认删除对话框
  Future<bool> _confirmDeleteUser(BuildContext context, int userId) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除此用户吗？此操作不可撤销。'),
        actions: [
          TextButton(
            child: const Text('取消'),
            onPressed: () => Navigator.pop(context, false),
          ),
          TextButton(
            child: const Text('删除', style: TextStyle(color: Colors.red)),
            onPressed: () => Navigator.pop(context, true),
          ),
        ],
      ),
    );
    return confirmed ?? false;
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.people_alt_outlined, size: 64, color: Colors.grey),
          const SizedBox(height: 16),
          const Text('暂无用户', style: TextStyle(fontSize: 18)),
          const SizedBox(height: 8),
          const Text('点击下方按钮添加新用户', style: TextStyle(color: Colors.grey)),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('添加用户'),
            onPressed: () => _showAddUserDialog(context),
          ),
        ],
      ),
    );
  }

  void _showAddUserDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => UserFormDialog(
        title: '添加用户',
        onSave: (newUser) => _createUser(newUser),
      ),
    );
  }

  void _showEditUserDialog(BuildContext context, User user) {
    showDialog(
      context: context,
      builder: (context) => UserFormDialog(
        title: '编辑用户',
        user: user,
        onSave: (updatedUser) => _updateUser(updatedUser),
      ),
    );
  }

  void _createUser(User user) async {
    setState(() => _isLoading = true);

    try {
      final createdUser = await context.read<UserService>().createUser(user);

      // 在实际应用中，这里应该更新用户列表
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('用户 "${createdUser.displayName}" 创建成功'),
          backgroundColor: Colors.green,
        ),
      );

      // 刷新用户列表
      _loadUsers();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('创建用户失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      setState(() => _isLoading = false);
      Navigator.pop(context); // 关闭对话框
    }
  }

  void _updateUser(User user) async {
    setState(() => _isLoading = true);

    try {
      final updatedUser = await context.read<UserService>().updateUser(user);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('用户 "${updatedUser.displayName}" 更新成功'),
          backgroundColor: Colors.green,
        ),
      );

      _loadUsers();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('更新用户失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      setState(() => _isLoading = false);
      Navigator.pop(context); // 关闭对话框
    }
  }

  void _deleteUser(int userId) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除此用户吗？此操作不可撤销。'),
        actions: [
          TextButton(
            child: const Text('取消'),
            onPressed: () => Navigator.pop(context, false),
          ),
          TextButton(
            child: const Text('删除', style: TextStyle(color: Colors.red)),
            onPressed: () => Navigator.pop(context, true),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    setState(() => _isLoading = true);

    try {
      final success = await context.read<UserService>().deleteUser(userId);

      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('用户删除成功'),
            backgroundColor: Colors.green,
          ),
        );

        _loadUsers();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('用户删除失败'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('删除用户失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  void _showUserDetails(BuildContext context, User user) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => DraggableScrollableSheet(
        expand: false,
        initialChildSize: 0.7,
        maxChildSize: 0.9,
        builder: (context, scrollController) {
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppBar(
                  title: Text(user.displayName),
                  centerTitle: true,
                  automaticallyImplyLeading: false,
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                Center(
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: NetworkImage(user.avatarUrl),
                  ),
                ),
                const SizedBox(height: 16),
                _buildDetailItem('姓名', user.name),
                _buildDetailItem('用户名', user.username),
                _buildDetailItem('邮箱', user.email),
                _buildDetailItem('电话', user.phone),
                _buildDetailItem('网站', user.website),
                if (user.address != null) ...[
                  const SizedBox(height: 16),
                  const Text('地址', style: TextStyle(fontWeight: FontWeight.bold)),
                  _buildDetailItem('街道', user.address!.street),
                  _buildDetailItem('门牌号', user.address!.suite),
                  _buildDetailItem('城市', user.address!.city),
                  _buildDetailItem('邮编', user.address!.zipcode),
                ],
                const Spacer(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    ElevatedButton.icon(
                      icon: const Icon(Icons.edit),
                      label: const Text('编辑'),
                      onPressed: () {
                        Navigator.pop(context);
                        _showEditUserDialog(context, user);
                      },
                    ),
                    ElevatedButton.icon(
                      icon: const Icon(Icons.delete, color: Colors.red),
                      label: const Text('删除', style: TextStyle(color: Colors.red)),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.white,
                        side: const BorderSide(color: Colors.red),
                      ),
                      onPressed: () {
                        Navigator.pop(context);
                        _deleteUser(user.id);
                      },
                    ),
                  ],
                ),
                // 添加查看帖子和评论的按钮
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton.icon(
                      icon: const Icon(Icons.article),
                      label: const Text('查看帖子'),
                      onPressed: () {
                        Navigator.pop(context); // 关闭详情面板
                        _navigateToUserPosts(context, user);
                      },
                    ),
                    ElevatedButton.icon(
                      icon: const Icon(Icons.comment),
                      label: const Text('查看评论'),
                      onPressed: () {
                        Navigator.pop(context); // 关闭详情面板
                        _navigateToUserComments(context, user);
                      },
                    ),
                  ],
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildDetailItem(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(value.isNotEmpty ? value : '无'),
          ),
        ],
      ),
    );
  }

  void _navigateToUserPosts(BuildContext context, User user) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostsScreen(
          userId: user.id,
          userName: user.displayName,
        ),
      ),
    );
  }

  void _navigateToUserComments(BuildContext context, User user) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CommentsScreen(
          userId: user.id,
          userName: user.displayName,
        ),
      ),
    );
  }

/*
  写在当前页，不适合
  void _navigateToUserComments(BuildContext context, User user) {
    // 假设我们有专门的用户评论页面
    // 这里可以创建或跳转到用户评论页面
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('${user.displayName}的评论'),
        content: FutureBuilder<List<Comment>>(
          future: context.read<CommentService>().getCommentsByUser(user.id),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }

            if (snapshot.hasError) {
              return Text('加载评论失败: ${snapshot.error}');
            }

            final comments = snapshot.data ?? [];

            if (comments.isEmpty) {
              return const Text('该用户还没有发表评论');
            }

            return SizedBox(
              width: double.maxFinite,
              height: MediaQuery.of(context).size.height * 0.6,
              child: ListView.builder(
                itemCount: comments.length,
                itemBuilder: (context, index) {
                  final comment = comments[index];
                  return Card(
                    child: ListTile(
                      title: Text(comment.name),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(comment.body),
                          const SizedBox(height: 4),
                          Text(
                            '帖子ID: ${comment.postId}',
                            style: const TextStyle(color: Colors.grey),
                          ),
                        ],
                      ),
                      onTap: () {
                        // 可以添加跳转到帖子详情的功能
                        Navigator.pop(context);
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('跳转到帖子 ${comment.postId}'),
                          ),
                        );
                      },
                    ),
                  );
                },
              ),
            );
          },
        ),
        actions: [
          TextButton(
            child: const Text('关闭'),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  }*/

  Widget _buildUserPostsTab() {
    return FutureBuilder<List<User>>(
      future: _futureUsers,
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data == null) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return CustomErrorWidget(
            message: snapshot.error.toString(),
            onRetry: _loadUsers,
          );
        }

        final users = snapshot.data!;
        return Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '选择用户查看其帖子',
                style: Theme.of(context).textTheme.titleMedium,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: users.length,
                itemBuilder: (context, index) {
                  final user = users[index];
                  return FutureBuilder<List<Post>>(
                    future: context.read<PostService>().getPostsByUser(user.id),
                    builder: (context, postSnapshot) {
                      final postCount = postSnapshot.data?.length ?? 0;

                      return ListTile(
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(user.avatarUrl),
                        ),
                        title: Text(user.displayName),
                        subtitle: Text('帖子数: $postCount'),
                        trailing: const Icon(Icons.arrow_forward),
                        onTap: () => _navigateToUserPosts(context, user),
                      );
                    },
                  );
                },
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildUserCommentsTab() {
    return FutureBuilder<List<User>>(
      future: _futureUsers,
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data == null) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return CustomErrorWidget(
            message: snapshot.error.toString(),
            onRetry: _loadUsers,
          );
        }

        final users = snapshot.data!;
        return Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                '选择用户查看其评论',
                style: Theme.of(context).textTheme.titleMedium,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: users.length,
                itemBuilder: (context, index) {
                  final user = users[index];
                  return FutureBuilder<List<Comment>>(
                    future: context.read<CommentService>().getCommentsByUser(user.id),
                    builder: (context, commentSnapshot) {
                      final commentCount = commentSnapshot.data?.length ?? 0;

                      return ListTile(
                        leading: CircleAvatar(
                          backgroundImage: NetworkImage(user.avatarUrl),
                        ),
                        title: Text(user.displayName),
                        subtitle: Text('评论数: $commentCount'),
                        trailing: const Icon(Icons.arrow_forward),
                        onTap: () => _navigateToUserComments(context, user),
                      );
                    },
                  );
                },
              ),
            ),
          ],
        );
      },
    );
  }
}